package top.honlnk.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.honlnk.common.constant.PublicConstant;
import top.honlnk.common.exception.CustomException;
import top.honlnk.common.utils.StringToArrayUtil;
import top.honlnk.mapper.PublicMapper;
import top.honlnk.pojo.entity.RotaSecretKey;
import top.honlnk.pojo.vo.AdminGetRotaListVO;
import top.honlnk.pojo.vo.AdminGetRotaVO;
import top.honlnk.pojo.vo.KeyValidationResultVO;
import top.honlnk.service.AdminService;
import top.honlnk.service.impl.processor.AnalysisAdminKeyProcessor;
import top.honlnk.service.PublicService;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Slf4j
@Service
public class PublicServiceImpl implements PublicService {

    @Autowired
    private PublicMapper publicMapper;

    @Autowired
    AdminService adminService;

    @Override
    public void validateKey(String key, boolean isAdmin) {
        // 根据模糊查询，获取密钥，如果能获取的出来，说明这个密钥是正确的，反之，则抛出异常：密钥不正确
        RotaSecretKey rotaSecretKey = publicMapper.getRotaSecretKeyLike(key);
        if (rotaSecretKey == null) {
            throw new CustomException("您的密钥不正确，请重新检查密钥");
        } else {
            // 代码进入这里说明密钥正确，接下来要判断密钥权限，如果key与存储的密钥一致，说明是管理员，反之，则不是
            // 如果isAdmin是true，说明是管理员相关操作判断正在判断密钥的正确性，key与存储的密钥必须保持一致，否则视为密钥无权限
            // 如果isAdmin是false，说明是用户相关操作判断正在判断密钥的正确性，key与存储的密钥不需要保持一致，所以视为密钥正确，方法正常通过
            if (isAdmin && !rotaSecretKey.getAdminKey().equals(key)) {
                throw new CustomException("您没有权限进行此操作");
            }
        }
    }

    @Override
    public List<KeyValidationResultVO> validateKeysList(List<String> keys) {
        // 获取数据库中的键列表
        List<RotaSecretKey> keyList = publicMapper.getKeyListLike(keys);

        // 创建一个结果列表来存储有效性信息
        List<KeyValidationResultVO> resultList = new ArrayList<>();

        // 遍历请求的键列表
        for (String key : keys) {
            // 初始化标志变量
            boolean isValid = false;

            // 遍历数据库中的键列表
            for (RotaSecretKey rotaSecretKey : keyList) {

                if (key.length() == 11) {
                    // 检查是否匹配
                    if (rotaSecretKey.getAdminKey().substring(0,  11).equals(key)) {
                        isValid = true;
                        break; // 如果找到了匹配项，退出循环
                    }
                } else if (key.length() == 22) {
                    if (rotaSecretKey.getAdminKey().equals(key)) {
                        isValid = true;
                        break;
                    }
                }
            }

            // 创建 KeyValidationResultVO 对象并设置状态
            KeyValidationResultVO vo = new KeyValidationResultVO();
            vo.setKey(key);
            vo.setValid(isValid);

            // 将对象添加到结果列表中
            resultList.add(vo);
        }

        // 返回结果列表
        return resultList;
    }
    @Override
    public void updateDatabase() {
        List<RotaSecretKey> rotaSecretKeys = publicMapper.getRotaSecretKey();
        AnalysisAdminKeyProcessor analysisAdminKeyProcessor = new AnalysisAdminKeyProcessor();
        for (RotaSecretKey rotaSecretKey : rotaSecretKeys) {
            String storedAdminKey = rotaSecretKey.getAdminKey();
            if (storedAdminKey != null) {
                LocalDate timeDifference = analysisAdminKeyProcessor.getTimeDifference(storedAdminKey);
                if (LocalDate.now().isAfter(timeDifference.plusDays(7)) || LocalDate.now().isEqual(timeDifference.plusDays(7))) {
                    int count = publicMapper.deleteSchoolTimetable(rotaSecretKey.getId());
                    publicMapper.deleteRotaSecretKey(rotaSecretKey.getId());
                    log.info(PublicConstant.KEY_EXPIRED_AUTO_DELETE, storedAdminKey, count);
                } else if (LocalDate.now().isEqual(timeDifference)) {
                    // 判断rota 是否为空，如果为空，则自动生成值班表
                    if (rotaSecretKey.getRota() == null || rotaSecretKey.getRota().isEmpty()) {
                        // 自动生成值班表
                        AdminGetRotaListVO adminGetRotaListVO = adminService.produceRota(storedAdminKey);
                        log.info(PublicConstant.KEY_AUTO_GENERATE_ROTA, storedAdminKey, Arrays.deepToString(adminGetRotaListVO.getRota().toArray()));
                    }
                } else {
                    log.info(PublicConstant.KEY_PLAN_NOT_EXECUTE, storedAdminKey, timeDifference, timeDifference.plusDays(7));
                }
            }
        }
    }

    @Override
    public AdminGetRotaVO getRota(String key) {

        RotaSecretKey rotaSecretKey = publicMapper.getRotaSecretKeyLike(key);
        String rotaString = rotaSecretKey.getRota();
        if (rotaString == null || rotaString.isEmpty()) {
            throw new CustomException(PublicConstant.NO_ROTA_YET);
        }
        StringToArrayUtil stringToArrayUtil = new StringToArrayUtil();
        String[][][] rota = stringToArrayUtil.stringTo3DArray(rotaString);

        return AdminGetRotaVO.builder().rota(rota).build();
    }


}
